//
//  GrantXPController.m
//  This file is part of D&D Manager
//
//  Created by Matthew Hutton on 14/02/2007.
//
//
//D&D Manager, a D&D Character and battle management program.
//Copyright (C) 2007, Matthew Hutton
//
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along with this program; if not, write to:
//The Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#import "GrantXPController.h"
#import "AbilityChanged.h"

@implementation GrantXPController
-(id)initWithCharacterController:(NSArrayController *)charController
				  withMainWindow:(NSWindow *)mainWindow{
	characterController=charController;
	mainScreen=mainWindow;
	[super initWithWindowNibName:@"Grant XP"];
	return self;
}
-(IBAction)grantXPFinished:(id)sender{
	[grantXPsheet orderOut:sender];
	[NSApp endSheet:grantXPsheet];
	int totalXP=[xpGranted intValue];

	BOOL mp=YES;
	NSString *pred=[[characterController filterPredicate] predicateFormat];
	NSObject *currentSelObj=[[characterController selectedObjects] objectAtIndex:0];
	if([grantXPParty selectedColumn]==0){
		[characterController setFilterPredicate:[NSPredicate predicateWithFormat:@"mainPartyMember==1"]];
	}else{
		mp=NO;
		[characterController setFilterPredicate:[NSPredicate predicateWithFormat:@"enemyPartyMember==1"]];
	}
	NSArray *array=[characterController arrangedObjects];
	if([array count]==0){
		//NSLog(@"no chars");
		NSBeginAlertSheet(@"No Characters in chosen party",@"OK",nil,nil,mainScreen,self,nil,nil,NULL,@"There are no characters in the chosen party so XP cannot be given.");
		return;
	}
	int xpGiven=totalXP/[array count];
	int i;
	for(i=0;i<[array count];i++){
		NSManagedObject *obj=[array objectAtIndex:i];
		[obj setValue:[NSNumber numberWithInt:([[obj valueForKey:@"xp"] intValue]+xpGiven)]
			   forKey:@"xp"];
		[AbilityChanged setLevelOrXPForChar:obj];
	}
	[characterController setFilterPredicate:[NSPredicate predicateWithFormat:pred]];
	[characterController setSelectedObjects:[NSArray arrayWithObject:currentSelObj]];
}
@end
